﻿using UnityEngine;
using System.Collections.Generic;

public class AStarAI : MonoBehaviour
{
    AStarClient aStarClient;
    Stack<Vector2Int> keyPoints;
    //bool isPath = false;
    public float Speed = 1f;
    void Start()
    {
        aStarClient = GetComponent<AStarClient>();
        Speed = HexagnoalMap.Instance.OuterRadius * 1.8f;
        keyPoints = new Stack<Vector2Int>(64);
        next = transform.position;
    }
    Vector3 next;
    private void Update()
    {
        //if (!isPath)
        //{
            if (Input.GetMouseButtonDown(1) && HexagnoalMap.Instance.MousePointCell != null)
            {
                Vector2Int end = HexagnoalMap.Instance.MousePointCell.Value;
                Vector2Int start = HexagnoalMap.Instance.GetCoor(transform.position);
                keyPoints.Clear();
                if (aStarClient.GetPath(start, end, keyPoints))
                {
                    //isPath = true;
                    next = transform.position;
                }
            }
        //}
        //else
        //{
            Vector3 dir = next - transform.position;
            if (dir.sqrMagnitude < 0.001f)
            {
                if (keyPoints.Count > 0)
                    next = HexagnoalMap.Instance.GetPosition(keyPoints.Pop());
            }
            else
            {
                transform.Translate(dir.normalized * Speed * Time.deltaTime);
            }
        //}
    }
}
